// Global chart instances
let charts = {
    timeDistribution: null,
    amountDistribution: null,
    featureDistribution: null,
    trainingAccuracy: null,
    validationAccuracy: null,
    tsneOriginal: null,
    tsneEngineered: null,
    transactionMonitor: null
};

/**
 * Initialize data exploration charts using Chart.js
 * Called after data processing is complete
 */
function initializeExplorationCharts() {
    // Time distribution chart (transactions over time)
    const timeCtx = document.getElementById('time-chart').getContext('2d');
    charts.timeDistribution = new Chart(timeCtx, {
        type: 'bar',
        data: {
            labels: ['0-20k', '20k-40k', '40k-60k', '60k-80k', '80k-100k', '100k-120k', '120k-140k', '140k-160k', '160k+'],
            datasets: [{
                label: 'Normal Transactions',
                data: [35000, 42000, 38000, 32000, 28000, 36000, 31000, 29000, 11500],
                backgroundColor: 'rgba(76, 175, 80, 0.7)',
                borderColor: 'rgba(76, 175, 80, 1)',
                borderWidth: 1
            }, {
                label: 'Fraudulent Transactions',
                data: [45, 62, 38, 55, 72, 68, 74, 58, 20],
                backgroundColor: 'rgba(244, 67, 54, 0.7)',
                borderColor: 'rgba(244, 67, 54, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: 'Number of Transactions'
                    }
                },
                x: {
                    title: {
                        display: true,
                        text: 'Time (seconds)'
                    }
                }
            },
            plugins: {
                legend: {
                    position: 'top',
                },
                title: {
                    display: true,
                    text: 'Transaction Distribution by Time'
                }
            }
        }
    });

    // Amount distribution chart (transaction values)
    const amountCtx = document.getElementById('amount-chart').getContext('2d');
    charts.amountDistribution = new Chart(amountCtx, {
        type: 'bar',
        data: {
            labels: ['$0-10', '$10-50', '$50-100', '$100-500', '$500-1000', '$1000+'],
            datasets: [{
                label: 'Normal Transactions',
                data: [85000, 95000, 65000, 35000, 3500, 815],
                backgroundColor: 'rgba(76, 175, 80, 0.7)',
                borderColor: 'rgba(76, 175, 80, 1)',
                borderWidth: 1
            }, {
                label: 'Fraudulent Transactions',
                data: [120, 145, 85, 110, 22, 10],
                backgroundColor: 'rgba(244, 67, 54, 0.7)',
                borderColor: 'rgba(244, 67, 54, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    type: 'logarithmic',
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: 'Number of Transactions (log scale)'
                    }
                },
                x: {
                    title: {
                        display: true,
                        text: 'Transaction Amount'
                    }
                }
            },
            plugins: {
                legend: {
                    position: 'top',
                },
                title: {
                    display: true,
                    text: 'Transaction Distribution by Amount'
                }
            }
        }
    });

    // Initialize feature distribution chart
    updateFeatureChart('V1');
}

/**
 * Update feature distribution chart based on selected feature
 * @param {string} feature - Selected feature (e.g., 'V1', 'V2')
 */
function updateFeatureChart(feature) {
    const ctx = document.getElementById('feature-chart').getContext('2d');
    
    // Destroy existing chart if it exists
    if (charts.featureDistribution) charts.featureDistribution.destroy();
    
    // Generate simulated distribution data
    const labels = Array.from({ length: 30 }, (_, i) => (i - 15).toFixed(1));
    const normalData = labels.map((_, i) => Math.exp(-0.03 * Math.pow(i - 15, 2)) * 100);
    const fraudData = labels.map((_, i) => Math.exp(-0.1 * Math.pow(i - 10, 2)) * 100);

    // Create new feature distribution chart
    charts.featureDistribution = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: 'Normal Transactions',
                data: normalData,
                borderColor: 'rgba(76, 175, 80, 1)',
                backgroundColor: 'rgba(76, 175, 80, 0.1)',
                tension: 0.4,
                fill: true
            }, {
                label: 'Fraudulent Transactions',
                data: fraudData,
                borderColor: 'rgba(244, 67, 54, 1)',
                backgroundColor: 'rgba(244, 67, 54, 0.1)',
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: 'Density'
                    }
                },
                x: {
                    title: {
                        display: true,
                        text: `${feature} Value`
                    }
                }
            },
            plugins: {
                legend: {
                    position: 'top',
                },
                title: {
                    display: true,
                    text: `Distribution of Feature ${feature}`
                }
            }
        }
    });
}

/**
 * Initialize training accuracy charts
 */
function initializeTrainingCharts() {
    // Training accuracy chart
    const accCtx = document.getElementById('accuracy-chart').getContext('2d');
    charts.trainingAccuracy = new Chart(accCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: 'Training Accuracy',
                data: [],
                borderColor: 'rgba(78, 115, 223, 1)',
                backgroundColor: 'rgba(78, 115, 223, 0.1)',
                fill: true,
                tension: 0.3
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    min: 0.9,
                    max: 1.0,
                    title: {
                        display: true,
                        text: 'Accuracy'
                    }
                },
                x: {
                    title: {
                        display: true,
                        text: 'Epoch'
                    }
                }
            },
            plugins: {
                legend: {
                    position: 'top'
                }
            }
        }
    });

    // Validation accuracy chart
    const valAccCtx = document.getElementById('val-accuracy-chart').getContext('2d');
    charts.validationAccuracy = new Chart(valAccCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: 'Validation Accuracy',
                data: [],
                borderColor: 'rgba(54, 185, 204, 1)',
                backgroundColor: 'rgba(54, 185, 204, 0.1)',
                fill: true,
                tension: 0.3
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    min: 0.9,
                    max: 1.0,
                    title: {
                        display: true,
                        text